package com.book.management.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.breakage.entity.Back;
import com.book.breakage.service.BackService;
import com.book.business.entity.BookIndent;
import com.book.business.service.BookSellService;
import com.book.common.utils.WareBook;
import com.book.business.service.BookIndentService;
import com.book.publishing.entity.BookMessage;
import com.book.publishing.service.BookMessageService;
import com.book.shelves.service.BookStoreService;
import com.book.common.annotation.ControllerEndpoint;
import com.book.common.annotation.Log;
import com.book.common.controller.BaseController;
import com.book.common.entity.FebsConstant;
import com.book.common.entity.FebsResponse;
import com.book.common.entity.QueryRequest;
import com.book.common.utils.FebsUtil;
import com.book.management.entity.Revocation;
import com.book.management.entity.SendBack;
import com.book.management.service.RevocationService;
import com.book.management.service.SendBackService;
import com.book.publishing.service.BookmanService;
import com.book.stat.entity.BreakageStat;
import com.book.stat.service.BreakageStatService;
import com.book.system.entity.Money;
import com.book.system.entity.User;
import com.book.system.service.IUserService;
import com.book.system.service.MoneyService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: 何胤宏
 * @Description: 20173969
 */

@Controller
public class SendBackController extends BaseController {
    @Autowired
    SendBackService sendBackService;
    @Autowired
    BookIndentService bookIndentService;
    @Autowired
    MoneyService moneyService;
    @Autowired
    IUserService userService;
    @Autowired
    BookStoreService bookStoreService;
    @Autowired
    RevocationService revocationService;
    @Autowired
    BookmanService bookmanService;
    @Autowired
    BookSellService bookSellService;
    @Autowired
    BookMessageService bookMessageService;
    @Autowired
    BackService backService;
    @Autowired
    BreakageStatService breakageStatService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "management/sendBack")
    public String toSendBackIndex() {
        return FebsUtil.view("management/sendBack/sendBackList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "management/sendBack/add")
    public String toSendBackAdd() {
        return FebsUtil.view("management/sendBack/sendBackAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "management/sendBookBack/add/{id}")
    public String toSendBookBack(@PathVariable Integer id, ModelMap modelMap) {
        BookIndent bookIndent = this.bookIndentService.getById(id);
        SendBack sendBack = new SendBack()
                .setBookname(bookIndent.getBookname())
                .setBooktype(bookIndent.getType())
                .setBookmoney(bookIndent.getBookmoney())
                .setIndentid(bookIndent.getId())
                .setPubid(bookIndent.getPubid())
                .setIndentdate(bookIndent.getOnetime())
                .setNumber(bookIndent.getNumber())
                .setPrincipal(bookIndent.getUsername())
                .setBookstatus(bookIndent.getFlag())
                .setBackdate(new Date())
                .setIndentedStatus(bookIndent.getStatus())
                .setBackstatus(bookIndent.getBackstatus())
                .setTotalmoney(bookIndent.getMoney());
        modelMap.put("sendBookBack", sendBack);
        return FebsUtil.view("management/sendBack/sendBookBack");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "management/sendBack/update/{ids}")
    public String toSendBackUpdate(@PathVariable Integer ids, ModelMap modelMap) {
        SendBack sendBack = sendBackService.getById(ids);
        modelMap.addAttribute("sendBack", sendBack);
        return FebsUtil.view("management/sendBack/sendBackUpdate");
    }

    @GetMapping("sendBack")
    @ResponseBody
    @RequiresPermissions("sendBack:view")
    public FebsResponse findSendBack(SendBack sendBack) {
        return new FebsResponse().success().data(sendBackService.listSendBack(sendBack));
    }

    @Log("访问退书信息")
    @GetMapping("sendBack/list")
    @ResponseBody
    @RequiresPermissions("sendBack:view")
    public FebsResponse sendBackListPage(QueryRequest request, SendBack sendBack) {
        Map<String, Object> dataTable = getDataTable(this.sendBackService.sendBackPage(request, sendBack));
        return new FebsResponse().success().data(dataTable);
    }

    @Log("退书-新增")
    @PostMapping("sendBack")
    @ResponseBody
    @RequiresPermissions("sendBack:add")
    @ControllerEndpoint(operation = "退书新增", exceptionMessage = "新增退书信息失败")
    public FebsResponse sendBackAdd(SendBack sendBack) {
        BookIndent bookIndent = bookIndentService.getOne(new QueryWrapper<BookIndent>().lambda()
                .eq(BookIndent::getBookname, sendBack.getBookname())
                .eq(BookIndent::getUsername, sendBack.getPrincipal())
                .eq(BookIndent::getPubid, sendBack.getPubid())
                .eq(BookIndent::getNumber, sendBack.getNumber())
                .eq(BookIndent::getOnetime, sendBack.getIndentdate()));
        if (bookIndent == null) {
            return new FebsResponse().message("抱歉，没有该订单，请进行核对！");
        }
        if (!"1".equals(bookIndent.getFlag())) {
            return new FebsResponse().message("该订单还未完成，概不审理。");
        }
        if ("1".equals(bookIndent.getBackstatus())) {
            return new FebsResponse().message("该订单正在报损申请中！");
        }
        if ("2".equals(bookIndent.getBackstatus())) {
            return new FebsResponse().message("该订单已经被审核过，不能退书！");
        }
        if ("3".equals(bookIndent.getBackstatus())) {
            return new FebsResponse().message("该订单正在审核中，请耐心等候！");
        }
        bookIndent.setBackstatus("3");
        sendBack.setStatus("0");
        sendBack.setIndentid(bookIndent.getId());
        sendBack.setBookstatus(bookIndent.getFlag());
        sendBack.setBooktype(bookIndent.getType());
        sendBack.setBackdate(new Date());
        bookIndentService.updateBookIndent(bookIndent);
        this.sendBackService.addSendBack(sendBack);
        return new FebsResponse().success();
    }

    @Log("退书-修改")
    @PostMapping("sendBack/update")
    @ResponseBody
    @RequiresPermissions("sendBack:update")
    @ControllerEndpoint(operation = "修改退书信息成功", exceptionMessage = "修改退书信息失败")
    public FebsResponse sendBackUpdate(SendBack sendBack) {
        this.sendBackService.updateSendBack(sendBack);
        return new FebsResponse().success();
    }

    @Log("退书-删除")
    @PostMapping("sendBack/delete/{ids}")
    @ResponseBody
    @RequiresPermissions("sendBack:delete")
    @ControllerEndpoint(operation = "删除成功", exceptionMessage = "删除失败")
    public FebsResponse sendBackDelete(@PathVariable String ids) {
        String[] attr = ids.split(",");
        List<SendBack> sendBackList = sendBackService.applySendBack(attr);
        for (int i = 0; i < sendBackList.size(); i++) {
            bookIndentService.removeById(sendBackList.get(i).getIndentid());
        }
        sendBackService.deleteSendBack(attr);
        return new FebsResponse().success();
    }

    @PostMapping("sendBack/sendBackOne")
    @ResponseBody
    @RequiresPermissions("sendBack:delete")
    @ControllerEndpoint(operation = "退书受理", exceptionMessage = "受理失败")
    public FebsResponse sendBackOne(SendBack sendBack) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance();
        String yearAndMonths = format.format(calendar.getTime());
        String[] yearAndMonth = yearAndMonths.split("-");
        BookIndent indent = bookIndentService.getById(sendBack.getIndentid());
        // 本年是否有相同书籍的退书信息
        Revocation revocation = revocationService.getOne(new QueryWrapper<Revocation>().lambda()
                .eq(Revocation::getBookname, indent.getBookname()).eq(Revocation::getYear, yearAndMonth[0]));
        // 加入统计信息
        if (revocation == null) {
            revocation = new Revocation()
                    .setBookname(indent.getBookname())
                    .setPubid(indent.getPubid())
                    .setNumber(indent.getNumber())
                    .setBooktype(indent.getType())
                    .setBookmoney(indent.getBookmoney())
                    .setYear(yearAndMonth[0]);
            revocationService.addRevocation(revocation);
        } else {
            revocation.setNumber(revocation.getNumber() + indent.getNumber());
            revocationService.updateRevocation(revocation);
        }
        // 拿到对应订单
        Money money = moneyService.getOne(new QueryWrapper<Money>().lambda().eq(Money::getBookindentid, indent.getBookindentid()));
        money.setType("2");
        User user = getCurrentUser();
        user.setMoney(user.getMoney() + indent.getMoney());
        WareBook.wareBookChange(indent.getBookname(), "增加", indent.getNumber());
        bookIndentService.removeById(indent.getId());
        // 拿到架存管理书籍
        moneyService.updateMoney(money);
        userService.updateMoney(user);
        return new FebsResponse().success();
    }

    @PostMapping("sendBack/sendBackTwo")
    @ResponseBody
    @RequiresPermissions("sendBack:delete")
    @ControllerEndpoint(operation = "退书受理", exceptionMessage = "退书失败")
    public FebsResponse sendBackTwo(SendBack sendBack) {
        BookIndent bookIndent = bookIndentService.getById(sendBack.getIndentid());
        if ("1".equals(bookIndent.getBackstatus())) {
            return new FebsResponse().message("该订单已经申请报损，请耐心等待！");
        }
        if ("2".equals(bookIndent.getBackstatus())) {
            return new FebsResponse().message("该订单已经强制完成，不能退书！");
        }
        if ("3".equals(bookIndent.getBackstatus())) {
            return new FebsResponse().message("该订单正在申请退书中...");
        }
        bookIndent.setBackstatus("3");
        bookIndentService.updateBookIndent(bookIndent);
        sendBack.setStatus("0");
        sendBack.setTotalmoney(sendBack.getNumber() * sendBack.getBookmoney());
        sendBackService.addSendBack(sendBack);
        return new FebsResponse().success();
    }

    @Log("退书-审批")
    @PostMapping("sendBack/apply/{ids}")
    @ResponseBody
    @RequiresPermissions("sendBack:apply")
    public FebsResponse sendBackApply(@PathVariable String ids) {
        String[] attr = ids.split(",");
        List<SendBack> sendBackList = sendBackService.applySendBack(attr);
        for (int i = 0; i < sendBackList.size(); i++) {
            if ("1".equals(sendBackList.get(i).getStatus())) {
                return new FebsResponse().message("该审核已被审批，无需重复操作！");
            }
            if ("2".equals(sendBackList.get(i).getStatus())) {
                return new FebsResponse().message("该审核已被驳回，不能再通过！");
            }
            BookIndent bookIndent = bookIndentService.getById(sendBackList.get(i).getIndentid());
            Back back = new Back()
                    .setIndentid(bookIndent.getId())
                    .setBookname(bookIndent.getBookname())
                    .setBookmoney(bookIndent.getBookmoney())
                    .setBooktype(bookIndent.getType())
                    .setMessage(bookIndent.getBackmessage())
                    .setPrincipal(bookIndent.getUsername())
                    .setPubid(bookIndent.getPubid())
                    .setUsername(getCurrentUser().getUsername())
                    .setNumber(bookIndent.getNumber())
                    .setMessage(sendBackList.get(i).getMessage())
                    .setTotalmoney(bookIndent.getMoney())
                    .setStatus("0");
            backService.backAdd(back);
            bookIndent.setBackstatus("1");
            bookIndentService.updateBookIndent(bookIndent);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            String finish = format.format(sendBackList.get(i).getBackdate());
            String year = finish.split("-")[0];
            Revocation revocation = revocationService.getOne(new QueryWrapper<Revocation>().lambda()
                    .eq(Revocation::getBookname, sendBackList.get(i).getBookname()).eq(Revocation::getYear, year));
            if (revocation == null) {
                revocation = new Revocation()
                        .setYear(year)
                        .setBookname(sendBackList.get(i).getBookname())
                        .setBookmoney(sendBackList.get(i).getBookmoney())
                        .setBooktype(sendBackList.get(i).getBooktype())
                        .setNumber(sendBackList.get(i).getNumber())
                        .setPubid(sendBackList.get(i).getPubid());
                revocationService.addRevocation(revocation);
            } else {
                revocation.setNumber(revocation.getNumber() + sendBackList.get(i).getNumber());
                revocationService.updateRevocation(revocation);
            }
            Calendar calendar = Calendar.getInstance();
            String yearAndMonths = format.format(calendar.getTime());
            String[] yearAndMonth = yearAndMonths.split("-");
            BreakageStat breakageStat = new BreakageStat()
                    .setBreakageid((bookIndent.getId()).toString())
                    .setBookfrom("2")
                    .setBookname(bookIndent.getBookname())
                    .setBooktype(bookIndent.getType())
                    .setPubid(bookIndent.getPubid())
                    .setBookmoney(bookIndent.getBookmoney())
                    .setNumber(bookIndent.getNumber())
                    .setYear(yearAndMonth[0])
                    .setMonth(yearAndMonth[1])
                    .setTotalmoney(bookIndent.getMoney())
                    .setOmit("0");
            breakageStatService.addCount(breakageStat);
            sendBackList.get(i).setStatus("1");
            sendBackService.updateSendBack(sendBackList.get(i));
        }
        return new FebsResponse().success();
    }

    @Log("退书-驳回")
    @PostMapping("sendBack/no/{ids}")
    @ResponseBody
    @RequiresPermissions("sendBack:no")
    public FebsResponse sendBackNo(@PathVariable String ids) {
        String[] attr = ids.split(",");
        List<SendBack> sendBackList = sendBackService.applySendBack(attr);
        for (int i = 0; i < sendBackList.size(); i++) {
            if ("1".equals(sendBackList.get(i).getStatus())) {
                return new FebsResponse().message("该审核已被通过，不能再进行驳回！");
            }
            if ("2".equals(sendBackList.get(i).getStatus())) {
                return new FebsResponse().message("该审核已被驳回，无需重复操作！");
            }
            BookIndent bookIndent = bookIndentService.getById(sendBackList.get(i).getIndentid());
            if (bookIndent != null) {
                bookIndent.setBackstatus("2");
                bookIndentService.updateBookIndent(bookIndent);
            }
            sendBackList.get(i).setStatus("2");
            sendBackService.updateSendBack(sendBackList.get(i));
        }
        return new FebsResponse().success();
    }
}
